<?php
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

class WeiXin extends BaseOauth{

	protected $GetRequestCodeURL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
	protected $GetAccessTokenURL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
	protected $Authorize = 'scope=snsapi_userinfo&state=123#wechat_redirect';
//	protected $Authorize = 'scope=snsapi_base&state=123#wechat_redirect';
	protected $ApiBase = 'https://api.weixin.qq.com/';

		/**
	 * 请求code
	 */
	public function getRequestCode($param = array()){
		//Oauth 标准参数
		$params = array(
			'appid'     	=> $this->AppKey,
			'redirect_uri'  => urlencode($this->Callback),
			'response_type' => 'code',
		);
		$params = array_merge($params, $param);

		//获取额外参数
		if($this->Authorize){
			parse_str($this->Authorize, $_param);
			if(is_array($_param)){
				$params = array_merge($params, $_param);
			} else {
				throw new Exception('AUTHORIZE配置不正确！');
			}
		}
		_redirect( $this->GetRequestCodeURL . '?' . http_build_query($params) );
	}

	public function getAccessToken($code, $extend = null){
		$params = array(
				'appid'     	=> $this->AppKey,
				'secret' => $this->AppSecret,
				'grant_type'    => 'authorization_code',
				'code'          => $code,
		);

		$data = $this->http($this->GetAccessTokenURL, $params, 'POST');
		$this->Token = $this->parseToken($data, $extend);
		return $this->Token;
	}

	public function call($api, $param = '', $method = 'GET', $multi = false){
		$params = array(
			'access_token'       => $this->Token['access_token'],
			'openid'             => $this->openid(),
			'lang'             => 'zh_CN'
		);

		$vars = $this->param($params, $param);
		$data = $this->http($this->url($api), $vars, $method, array(), $multi);
		return json_decode($data, true);
	}

	protected function parseToken($result, $extend){
		parse_str($result, $data);
		$data = array_merge($data, $extend);
		if($data['access_token'] && $data['expires_in'] && $data['openid'])
			return $data;
		else
			throw new Exception("获取微信 ACCESS_TOKEN 出错：{$result}");
	}

	public function openid(){
		$data = $this->Token;
		if(isset($data['openid']))
			return $data['openid'];
		else
			throw new Exception('没有获取到openid！');
	}

	public function getuserinfo($token){
		$data = $this->call('sns/userinfo');

		if($data['ret'] == 0){
			$userInfo['type'] = 'WeiXin';
			$userInfo['name'] = $data['data']['nickname'];
			$userInfo['nick'] = $data['data']['nickname'];
			$userInfo['head'] = $data['data']['headimgurl'];
			return $userInfo;
		} else {
			throw_exception("获取微信用户信息失败：{$data['msg']}");
		}
	}
}
